import Taro, { Component, useEffect, useState } from '@tarojs/taro';
import { View, Image } from '@tarojs/components';
import './index.scss';
import back_img from '../../static/public/top_back.png';

import { setting as getSetting } from '../../services/program';

function NavigationBar(props) {
  const [statusBarHeight, setStatusBarHeight] = useState(0);
  const [backIconWidth, setBackIconWidth] = useState('');
  const [navigationBarHeight, setNavigationBarHeight] = useState(0);
  const [titleHeight, setTitleHeight] = useState(0);
  const [backgroundColor, setBackgroundColor] = useState('#000');
  const [fontColor, setFontColor] = useState('#fff');
  const [back, setBack] = useState(false);
  const [backIcon, setBackIcon] = useState('');

  useEffect(() => {
    if (Taro.getCurrentPages().length > 1 || props.type === 'activity' || props.type === 'home' || props.type === 'bindcard') {
      setBack(true);
    }
    const system = Taro.getStorageSync('system');
    setStatusBarHeight(system.statusBarHeight + 'px');
    setNavigationBarHeight(system.titleBarHeight + system.statusBarHeight + 'px');
    setTitleHeight(system.titleBarHeight + 'px');
    let setting = Taro.getStorageSync('setting');
    if (!setting) {
      console.log('没有获取到setting');
      getSetting().then(res => {
        setting = res;
        setBackIcon(back_img);
        Taro.setStorageSync('setting', res)
      });
    } else {
      setBackIcon(back_img);
    }
    if (props.backIcon) {
      setBackIconWidth("width: 35rpx")
      setBackIcon(props.backIcon)
    }
  }, []);

  function goBack() {
    if (props.type === 'bindcard') {
      return Taro.reLaunch({ url: '/pages/home/index' });
    }
    if (props.type === 'angentremark') {
      return Taro.reLaunch({ url: '/pages/user/index' });
    }
    if (props.type === 'activity' || Taro.getCurrentPages().length > 1) {
      Taro.navigateBack();

    } else {
      Taro.reLaunch({ url: '/pages/home/index' });
    }
  }

  return (
    <View>
      <View
        className='navbar'
        style={`height: ${navigationBarHeight}; background-color: ${backgroundColor};`}
      >
        <View style={statusBarHeight ? { height: statusBarHeight } : {}}></View>
        <View className='title-container' style={titleHeight ? { height: titleHeight } : {}}>
          {back && (
            <View className='capsule' onClick={goBack}>
              <Image style={backIconWidth ? backIconWidth : null} className='image-back' src={backIcon} />
            </View>
          )}
          <View className='title' style="color: #fff">
            {props.text}
          </View>
        </View>
      </View>
    </View>
  );
}
